
/*
 * 文件名：ExcelUtil.java
 * 修改人：chenliang
 * 修改时间：2018年8月11日
 * 修改内容：
 */

package com.kalvan.admin.excel;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.validation.BeanValidationResult;
import cn.hutool.extra.validation.ValidationUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.kalvan.client.constant.CommonReturnCode;
import com.kalvan.client.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * excel 工具
 *
 * @author chenliang
 */
@Slf4j
public class ExcelUtil {

    /**
     * excel下载
     *
     * @param fileName  文件名
     * @param response  response
     * @param pojoClass java对象
     * @param data      数据集合
     * @throws Exception Exception
     */
    public static void download(String fileName, HttpServletResponse response, Class pojoClass, List data) throws Exception {
        fileName = fileName + ".xlsx" ;
        response.setContentType("multipart/form-data");
        response.setHeader("filename", URLEncoder.encode(fileName, "utf-8"));
        EasyExcel.write(response.getOutputStream(), pojoClass).registerWriteHandler(new CustomCellWriteHandler()).sheet(0).doWrite(data);
    }


    /**
     * 模板文件下载 相对路径 /static/template/xx.file
     *
     * @param filepath filepath
     * @param response response
     * @throws Exception Exception
     */
    public static void downloadTemplate(String filepath, HttpServletResponse response) throws Exception {
        String basePath = new File(ExcelUtil.class.getResource("/").getPath()).toString();
        filepath = basePath + File.separator + filepath;
        String fileName = filepath.substring(filepath.lastIndexOf("/") + 1);
        response.setContentType("multipart/form-data");
        response.setHeader("filename", URLEncoder.encode(fileName, "utf-8"));
        OutputStream out = response.getOutputStream();
        try {
            InputStream is = new FileInputStream(new File(filepath));
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            bis.close();
            is.close();
            out.close();
        } catch (Exception e) {
            log.error("下载模板文件异常", e);
            throw new BizException(CommonReturnCode.ERROR.formatDesc("下载模板文件异常"));
        }

    }

    /**
     * excel 导入
     *
     * @param file       上传excel文件
     * @param sheet      sheet 页从1开始
     * @param headerRows 表头占前几行 从0 开始
     * @param pojoClass  转换成java对象
     * @return T
     * @throws Exception Exception
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer sheet, Integer headerRows, Class pojoClass)
            throws Exception {
        if (file == null) {
            throw new BizException(CommonReturnCode.PARAM_VALIDATE_ERROR.formatDesc("导入文件为空"));
        }

        InputStream inputStream = file.getInputStream();
        final List<T> rows = new ArrayList();
        // 解析每行结果在listener中处理
        AnalysisEventListener analysisEventListener = new AnalysisEventListener() {
            @Override
            public void invoke(Object object, AnalysisContext context) {
                //验证导入对象
                BeanValidationResult validate = ValidationUtil.warpValidate(object);
                if (!validate.isSuccess()) {
                    throw new BizException(CommonReturnCode.PARAM_VALIDATE_ERROR.formatDesc(String.format("第%s行数据有误:%s", rows.size(), CollectionUtil.join(validate.getErrorMessages(), ","))));
                }
                rows.add((T) object);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
        };
        EasyExcel.read(inputStream, pojoClass, analysisEventListener).sheet(0).headRowNumber(1).doRead();
        return rows;
    }

}
